package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.SysUserLike;
import com.mars.module.admin.mapper.SysUserLikeMapper;
import com.mars.module.admin.service.ISysDictDataService;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysCommunityRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysCommunityMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysCommunity;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysCommunityService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 社区业务层处理
 *
 * @author mars
 * @date 2024-04-04
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysCommunityServiceImpl implements ISysCommunityService {

    private final SysCommunityMapper baseMapper;
    private final SysUserMapper userMapper;
    private final SysUserLikeMapper likeMapper;
    private final ISysDictDataService iSysDictDataService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysCommunity add(SysCommunityRequest request) {
        SysCommunity entity = SysCommunity.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setCreateById(userId);
        entity.setUserId(userId);
        entity.setStatus("0");//默认是未审核状态
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysCommunityRequest request) {
        SysCommunity entity = SysCommunity.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysCommunity getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysCommunity> pageList(SysCommunityRequest request) {
        Page<SysCommunity> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysCommunity> query = this.buildWrapper(request);
        IPage<SysCommunity> pageRecord = baseMapper.selectPage(page, query);
        List<SysCommunity> records = pageRecord.getRecords();
        List<SysCommunity> recordsNew = new ArrayList<>();
        Long userId = ContextUserInfoThreadHolder.get().getId();
        for (SysCommunity news : records) {
            news.setStatus(iSysDictDataService.getDictDataById("community_type", news.getStatus()));
            SysUser sysUser = userMapper.selectById(news.getUserId());
            news.setUserName(sysUser == null ? "" : sysUser.getUserName());
            news.setAvatar(sysUser == null ? "" : sysUser.getAvatar());
            Long l = likeMapper.selectCount(new QueryWrapper<SysUserLike>().eq("user_id", userId).eq("community_id", news.getId()));
            if (l > 0) {
                news.setIsLike("1");
            } else {
                news.setIsLike("0");
            }
            news.setClassName(iSysDictDataService.getDictDataById("community_class", news.getClassId().toString()));
            recordsNew.add(news);
        }
        recordsNew = recordsNew.stream().sorted((m1, m2) -> m2.getCreateTime().compareTo(m1.getCreateTime())).collect(Collectors.toList());
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysCommunity> list(SysCommunityRequest request) {
        LambdaQueryWrapper<SysCommunity> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysCommunity> buildWrapper(SysCommunityRequest param) {
        LambdaQueryWrapper<SysCommunity> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getTitle())) {
            query.like(SysCommunity::getTitle, param.getTitle());
        }
        if (StringUtils.isNotBlank(param.getContent())) {
            query.like(SysCommunity::getContent, param.getContent());
        }
        if (StringUtils.isNotBlank(param.getUrl())) {
            query.like(SysCommunity::getUrl, param.getUrl());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.like(SysCommunity::getStatus, param.getStatus());
        }
        if (param.getUserId() != null) {
            query.like(SysCommunity::getUserId, param.getUserId());
        }
        if (param.getClassId() != null) {
            query.like(SysCommunity::getClassId, param.getClassId());
        }
        return query;
    }

}
